import requests
import re
import os
import time
import tkinter
import tkinter.messagebox
from bs4 import BeautifulSoup
from subprocess import run
login_url = 'http://172.30.16.34/srun_portal_pc.php?ac_id=5&'
name='此程序由云端筑梦进行开发与更新'
http='https://gitee.com/dream-in-the-clouds'
headers_data = {
    'Host': '10.32.254.11',
    'Connection': 'keep-alive',
    'Content-Length': '105',
    'Accept': '*/*',
    'X-Requested-With': 'XMLHttpRequest',
    'Origin': 'http://10.32.254.11',
    'Referer': 'http://10.32.254.11/a79.htm',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.80 Safari/537.36 Edg/86.0.622.43',
    'Accept-Encoding': 'gzip, deflate',
    'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',

}
#段落主体

def check():
    # 检查是否连入校园网
    i = 1
    while i>0:
        time.sleep(4)
        if ping():
            i=i-1
        else:
            return
    if i==0:
        i=1
    while i > 0:
        try:
            post_url = 'http://10.32.254.11/drcom/chkstatus?callback=dr1002'
            post_data = {
                'callback': 'dr1002'
            }
            response = requests.get(post_url, data=post_data, headers=headers_data)
            break
        except requests.exceptions.ConnectionError:
            print("连接超时了")
            time.sleep(6)
            i = i - 1
    else:
        if test2('多次连接发现有问题，\n是否需要退出自动程序?'):
            exit(0)
        else:
            time.sleep(2)
            return

    status = re.compile('result":(.*?),').findall(response.content.__str__())[0]
    if status == '0':
        enter()
    elif status == '1':
        time.sleep(6)




def login(username, password):
    # 登录校园网
    post_url = 'http://10.32.254.11:801/eportal/portal/login?callback=dr1003&user_account=%2C0%2C' + username + '&user_password=' + password
    post_data = {
        'callback': 'dr1003',
    }
    response = requests.post(post_url, data=post_data, headers=headers_data)
    if (
            b'dr1003({"result":0,"msg":"AC\xe8\xae\xa4\xe8\xaf\x81\xe5\xa4\xb1\xe8\xb4\xa5","ret_code":1});' == response.content):
        post_url = 'http://10.32.254.11/drcom/login'
        post_data = {
            'callback': 'dr1003',
            'DDDDD': username,
            'upass': password,
            '0MKKey': password,
        }
        response = requests.post(post_url, data=post_data, headers=headers_data)
    result = re.compile('msga=\\\\\'(.*?)\\\\\';', re.S).findall(response.content.__str__())
    # 1代表用户名错误，2代表密码错误
    if len(result) != 0:
        result = result[0]
        print(result)
    else:
        result = ''
    if result == 'userid error1':
        test1('用户名错误！\n请检查文件中用户名是否输入正确！')
        exit(0)
    elif result == 'userid error2':
        test1('密码错误！\n请检查文件中密码是否输入正确！')
        exit(0)
    elif result == '':
         print('succeeded!')
    elif result=='ldap auth error':
        test1('身份验证失败，请检查用户名和密码是否正确！')
        exit(0)
    else:
        test1('不知道的错误，建议反馈')
        exit(0)




def enter():
    # 读取用户名和密码
    fp = open('tool.txt', 'r')
    lines = fp.readlines()
    username = lines[0].split("username:")[1].strip()
    password = lines[1].split("password:")[1]
    fp.close()
    login(username, password)




#消息输入函数
def test2(message):
    root=tkinter.Tk()
    result = tkinter.messagebox.askokcancel(title='校园网小助手提醒你', message=message)
    root.destroy()
    return result


def test1(message):
    root = tkinter.Tk()
    result = tkinter.messagebox.showwarning(title='校园网小助手提醒你', message=message)
    root.destroy()
    return result




def new():
    #版本更新函数
    if ping():
        return
    else:
        ver1 = 'v1.0'  # 版本更新
        VERSION_URL = 'https://gitee.com/dream-in-the-clouds/auto_login/tags'  # 最新版本号url
        try :
            ver = requests.get(VERSION_URL)# 获取最新版本号
        except:
            return
        ver = BeautifulSoup(ver.text, "lxml")
        ver = ver.find(name='div', attrs={'class': 'tag-item-action tag-name'})
        ver = ver.text.strip()
        if ver1 != ver:
            if float(ver.strip('v')) - float(ver1.strip('v')) < 1:
                if test2('软件已有更新，是否进行更新呢？'):
                    os.system('start https://gitee.com/dream-in-the-clouds/auto_login/releases/' + ver)
                    exit(0)
                else:
                    return
            else:
                test1('软件已出最新版了\n请更新版本后使用~')
                os.system('start https://gitee.com/dream-in-the-clouds/auto_login/releases/' + ver)
                exit(0)




def main():
    #主函数
    result = test1('软件已经启动成功\n开发：云端筑梦')

def ping():
    #ping百度
    #0是ping通

    return run('ping -n 1 www.baidu.com',shell=True).returncode




if __name__ == '__main__':
    main()
    new()
    while 1:
       check()